<?php

if(!defined('STARGB_PATH')) {
    define('STARGB_PATH', MODX_BASE_PATH . 'assets/modules/stargb/');
}
if(!defined('STARGB_URL')) {
    define('STARGB_URL', MODX_BASE_URL . 'assets/modules/stargb/');
}

// language
require_once STARGB_PATH . 'StarLng.php';
if (file_exists(STARGB_PATH . 'lng/'.$modx->config['manager_language'].'.ini')) {
    StarLng::load(STARGB_PATH . 'lng/'.$modx->config['manager_language'].'.ini');
}

// variabled
$set = array();
$set['tpl'] = $tpl = 'stargb_tpl';
$set['msg'] = $msg = 'stargb_msg';
$set['comment'] = $comment = 'stargb_comment';
$set['form'] = $msg = 'stargb_form';
$set['subform'] = $subform = 'stargb_subform';

define('TOPICS_ON_PAGE', 10);

// StarGB
require_once STARGB_PATH . 'StarGB.php';

$gb = new StarGB($modx, $GLOBALS);

if ((!empty($_POST['message']))and(!empty($_POST['author']))) {
    $gb->addMessage($_POST['author'], $_POST['email'], $_POST['message'], $_POST['reply']);
}

$all_pages_num  = $gb->getPagesNum( TOPICS_ON_PAGE );
$current_page   = isset($_GET['page'])?intval($_GET['page']):1;
$page_offset    = ($current_page - 1)*TOPICS_ON_PAGE; 

$sql = "SELECT * FROM `{$gb->prefix}star_gb` WHERE parent_id='0' and ((approved = 1) OR (ip = '{$_SERVER['REMOTE_ADDR']}')) ORDER BY id DESC LIMIT {$page_offset}, " . TOPICS_ON_PAGE ;
$data = $gb->fetchAll($sql);

$content = '';
$odd = false;
foreach ($data as $row) {

    $msgdata = $gb->prepareData( $row, $odd );
    $content .= $modx->parseChunk($set['msg'], $msgdata, '[+', '+]');

    $odd = !$odd;
    foreach ($gb->fetchComments( $row['id'] ) as $comment) 
    {
        $content .= $modx->parseChunk($set['comment'], $gb->prepareData( $comment, $odd ), '[+', '+]'); 
        $odd = !$odd;
    }

    $content .= $modx->parseChunk($set['subform'], array('post_id'=>$row['id']), '[+', '+]');
}

function getPageHref($page, $text)
{
    return "<a href='guestbook.html?page={$page}'>{$text}</a>";
}

$page_nav       = '';
foreach (range(1, $all_pages_num) as $index) 
{
    $active_class = ($index == $current_page)?'active':'';
    $page_nav   .= "<li class='{$active_class}'>".getPageHref($index, $index)."</li>";
}

$page_nav       = "<ul class='pagination'>{$page_nav}</ul>";

$prev_page_nav  = ($current_page <= 1)?'':'<div class="prev_pagination">'.getPageHref($current_page-1, '&lt;&lt;').'</div>';
$next_page_nav  = ($current_page >= $all_pages_num)?'':'<div class="next_pagination">'.getPageHref($current_page+1, '&gt;&gt;')."</div>";

$modx->setPlaceholder('form', $modx->getChunk($set['form']));
$modx->setPlaceholder('content', $content);

$modx->setPlaceholder('page_nav', $page_nav);
$modx->setPlaceholder('prev_page_nav', $prev_page_nav);
$modx->setPlaceholder('next_page_nav', $next_page_nav);

// Return the chunk
echo $modx->getChunk($set['tpl']);
//$gb->dispatch('snippet');
//echo 'StarGB';
